<?php

class JamaahController extends BackEndController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //	public $layout='//layouts/column2';
    public $dir_img_tmp_full = "tmp";
    public $dir_img_full = "img/jamaah/foto";
    public $full_width = 354;
    public $full_height = 472;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            //	array('allow',  // allow all users to perform 'index' and 'view' actions
            //				'actions'=>array('index','view'),
            //				'users'=>array('*'),
            //			),
            array(
                'allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array(
                    'create',
                    'update',
                    'CropFoto',
                    'CropKtp',
                    'Upload',
                    'GetListKelompok',
                    'Import',
                    'admin',
                    'delete'),
                'expression' => '$user->isHaveAccess()',),
            array(
                'deny', // deny all users
                'users' => array('*'),),);
    }

    /**
     * Displays a particular model.
     *
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),));
    }

    protected function aftersave($filename) {
        if (isset($_POST['image_url'])) {
            $image = $this->dir_img_tmp_full . DS;
            $image .= pathinfo($_POST['image_url'], PATHINFO_BASENAME);
            $this->Croping($image, $this->dir_img_full, $filename, $this->full_width, $this->full_height);
            unlink($image);
        }
        if (isset($_POST['ktp_url'])) {
            $image = $this->dir_img_tmp_full . DS;
            $image .= pathinfo($_POST['ktp_url'], PATHINFO_BASENAME);
            $this->CropingKtp($image, $this->dir_img_full, $filename, $this->full_width, $this->full_height);
            unlink($image);
        }
        $this->redirect(array('jamaah/admin'));
        app()->end();
    }

    public function actionGetListKelompok() {
        u::auto_complete_kelompok();
        Yii::app()->end();
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Jamaah;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Jamaah'])) {
            $_POST['Jamaah']['tgl_lahir'] = date2sql($_POST['Jamaah']['tgl_lahir'], 'dd-mm-yy');
            $model->attributes = $_POST['Jamaah'];
            if ($model->save()) {
                $this->aftersave($model->id_laskar);
            }
            //	$this->redirect(array('view','id'=>$model->id_laskar));
        }
        $this->render('create', array(
            'model' => $model,));
    }

    public function actionImport() {
        if (isset($_FILES['jamaah_import'])) {
            $target_path = root() . '/tmp/';
            $file_excel = $target_path . basename($_FILES['jamaah_import']['name']);
            if (move_uploaded_file($_FILES['jamaah_import']['tmp_name'], $file_excel)) {
                Yii::import('application.vendors.PHPExcel', true);
                $objReader = PHPExcel_IOFactory::createReaderForFile($file_excel);
                $objPHPExcel = $objReader->load($file_excel); //$file --> your filepath and filename
                $counter_jamaah = $counter_kabupaten = $counter_kelompok = 0;
                for ($sheet = 0; $sheet < $objPHPExcel->getSheetCount(); $sheet++) {
                    $objPHPExcel->setActiveSheetIndex($sheet);
                    $objWorksheet = $objPHPExcel->getActiveSheet();
                    $title_sheet = strtolower($objWorksheet->getTitle());
                    if ($title_sheet != "putra" && $title_sheet != "putri"
                    ) {
                        continue;
                    }
                    $gender = $title_sheet == "putra" ? 0 : 1;
                    $highestRow = $objWorksheet->getHighestRow(); // e.g. 10
                    $highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
                    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
                    //echo '<table>' . "\n";
                    for ($row = 2; $row <= $highestRow; ++$row) {
                        //echo '<tr>' . "\n";
                        $regional = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
                        $wilayah =
                                $regional == "Barat" ? "Barat" : $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
                        $kabupaten = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
                        $kelompok = $objWorksheet->getCellByColumnAndRow(4, $row)->getValue();
                        $nama = $objWorksheet->getCellByColumnAndRow(5, $row)->getValue();
                        $almt_ktp = $objWorksheet->getCellByColumnAndRow(6, $row)->getValue();
                        $no_ktp = $objWorksheet->getCellByColumnAndRow(7, $row)->getValue();
                        $tmp_lahir = $objWorksheet->getCellByColumnAndRow(8, $row)->getValue();
                        $tgl_lahir = $objWorksheet->getCellByColumnAndRow(9, $row)->getValue();
                        $pekerjaan = $objWorksheet->getCellByColumnAndRow(10, $row)->getValue();
                        $pekerjaan_lain = $objWorksheet->getCellByColumnAndRow(11, $row)->getValue();
                        $hp1 = $objWorksheet->getCellByColumnAndRow(12, $row)->getValue();
                        $hp2 = $objWorksheet->getCellByColumnAndRow(13, $row)->getValue();
                        $tlp_rumah = $objWorksheet->getCellByColumnAndRow(14, $row)->getValue();
                        $pin_bb = $objWorksheet->getCellByColumnAndRow(15, $row)->getValue();
                        $email = $objWorksheet->getCellByColumnAndRow(16, $row)->getValue();
                        $almt_domisili = $objWorksheet->getCellByColumnAndRow(17, $row)->getValue();
                        $sa78 = $objWorksheet->getCellByColumnAndRow(18, $row)->getValue();
                        $laqodja = $objWorksheet->getCellByColumnAndRow(19, $row)->getValue();
                        $sad = $objWorksheet->getCellByColumnAndRow(20, $row)->getValue();
                        $qod = $objWorksheet->getCellByColumnAndRow(21, $row)->getValue();
                        $lama_suluk = $objWorksheet->getCellByColumnAndRow(22, $row)->getValue();
                        if ($nama == "") {
                            continue;
                        }
                        $k_id = Kelompok::model()->find("nama_kelompok = :nama", array('nama' => $kelompok));
                        if ($k_id == null) {
                            $kabupaten_id =
                                    Kabupaten::model()->find("nama_kabupaten = :nama", array('nama' => $kabupaten));
                            if ($kabupaten_id == null) {
                                $kode_lokasi = 0;
                                if (strtolower($regional) == 'timur' && strtolower($wilayah) == 'selatan') {
                                    $kode_lokasi = TIMURSELATAN;
                                }
                                if (strtolower($regional) == 'timur' && strtolower($wilayah) == 'tengah') {
                                    $kode_lokasi = TIMURTENGAH;
                                }
                                if (strtolower($regional) == 'timur' && strtolower($wilayah) == 'utara') {
                                    $kode_lokasi = TIMURUTARA;
                                }
                                if (strtolower($regional) == 'tengah' && strtolower($wilayah) == 'selatan') {
                                    $kode_lokasi = TENGAHSELATAN;
                                }
                                if (strtolower($regional) == 'tengah' && strtolower($wilayah) == 'tengah') {
                                    $kode_lokasi = TENGAHTENGAH;
                                }
                                if (strtolower($regional) == 'tengah' && strtolower($wilayah) == 'timur') {
                                    $kode_lokasi = TENGAHTIMUR;
                                }
                                if (strtolower($regional) == 'barat' && strtolower($wilayah) == 'barat') {
                                    $kode_lokasi = BARATBARAT;
                                }
                                $model_kabupaten = new Kabupaten;
                                $model_kabupaten->nama_kabupaten = ucwords($kabupaten);
                                $model_kabupaten->kode_lokasi = $kode_lokasi;
                                $model_kabupaten->save();
                                $counter_kabupaten++;
                                $kabupaten_id = $model_kabupaten;
                            }
                            $model_kelompok = new Kelompok;
                            $model_kelompok->nama_kelompok = ucwords($kelompok);
                            $model_kelompok->id_kabupaten = $kabupaten_id->id_kabupaten;
                            $model_kelompok->save();
                            $counter_kelompok++;
                            $k_id = $model_kelompok;
                        }
                        $j = Jamaah::model()->find("nama=:nama", array('nama' => $nama));
                        if ($j == null) {
                            $j = new Jamaah;
                        }
                        if ($j->tgl_gabung == null)
                            $j->tgl_gabung = date2sql(new DateTime(), 'yyyy - MM - dd');
                        $j->nama = ucwords($nama);
                        $j->jenis_kelamin = $gender;
                        $j->alamat_ktp = $almt_ktp == null ? "-" : $almt_ktp;
                        $j->no_ktp = $no_ktp == null ? "-" : $no_ktp;
                        $j->tempat_lahir = $tmp_lahir == null ? "-" : $tmp_lahir;
                        $j->tgl_lahir = date2sql($tgl_lahir == null ? new DateTime() : $tgl_lahir, 'yyyy - MM - dd');
//                        $j->pekerjaan = $pekerjaan == null ? "-" : $pekerjaan;
//                        $j->pekerjaan_lain = $pekerjaan_lain == null ? "-" : $pekerjaan_lain;
                        $j->hp1 = $hp1 == null ? "-" : $hp1;
                        $j->hp2 = $hp2 == null ? "-" : $hp2;
                        $j->tlp_rumah = $tlp_rumah == null ? "-" : $tlp_rumah;
                        $j->pin_bb = $pin_bb == null ? "-" : $pin_bb;
                        $j->email = $email == null ? "-" : $email;
//                        $j->alamat_domisili = $almt_domisili == null ? "-" : $almt_domisili;
                        $j->sadziliyah = $sad == null ? 0 : $sad;
                        $j->sa78 = $sa78 == null ? 0 : $sa78;
                        $j->qodiriyah = $qod == null ? 0 : $qod;
                        $j->lama_suluk = $lama_suluk == null ? 0 : $lama_suluk;
                        $j->id_kelompok = $k_id->id_kelompok;
                        $j->status = 1;
                        $j->laqodja = $laqodja == null ? 0 : $laqodja;
                        $j->save();
                        if (count($j->errors) == 0) {
                            $counter_jamaah++;
                        }
                    }
                }
                unlink($file_excel);
                Yii::app()->user->setFlash('import', "$counter_kabupaten Kabupaten, $counter_kelompok Kelompok, $counter_jamaah Jamaah berhasil dibuat.");
            } else {
                Yii::app()->user->setFlash('import', 'File Excel gagal diupload.');
            }
        }
        $this->render('import');
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Jamaah'])) {
            $_POST['Jamaah']['tgl_lahir'] = date2sql($_POST['Jamaah']['tgl_lahir'], 'dd-mm-yy');
            if ($_POST['id_kelompok_auto'] == null) {
                $_POST['Jamaah']['id_kelompok'] = $_POST['id_kelompok_auto'];
            }
            ;
            $model->attributes = $_POST['Jamaah'];
            if ($model->save()) {
                $this->aftersave($model->id_laskar);
            }
            //	$this->redirect(array('view','id'=>$model->id_laskar));
        }
        $this->render('update', array(
            'model' => $model,));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     *
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax'])) {
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Jamaah');
        $this->render('index', array(
            'dataProvider' => $dataProvider,));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Jamaah('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Jamaah'])) {
            $model->attributes = $_GET['Jamaah'];
        }
        $this->render('admin', array(
            'model' => $model,));
    }

    public function actionCropFoto($fm) {
        $id = $fm;
        Yii::app()->clientScript->scriptMap = array(
            (YII_DEBUG ? 'jquery.js' : 'jquery.min.js') => false,);
        $imageUrl = bu() . '/' . $this->dir_img_tmp_full . '/' . $id;
        $this->renderPartial('cropImg', array('imageUrl' => $imageUrl), false, true);
    }

    public function actionCropKtp($fm) {
        $id = $fm;
        Yii::app()->clientScript->scriptMap = array(
            (YII_DEBUG ? 'jquery.js' : 'jquery.min.js') => false,);
        $imageUrl = bu() . '/' . $this->dir_img_tmp_full . '/' . $id;
        $this->renderPartial('cropKtp', array('imageUrl' => $imageUrl), false, true);
    }

    protected function Croping($image, $pathThumb, $name, $width, $height) {
        if (isset($_POST['cropID'])) {
            if (!file_exists($pathThumb)) {
                mkdir($pathThumb, 0777, true);
            }
            $coords = array(
                'x' => $_POST['AvatarForm_cropX'],
                'y' => $_POST['AvatarForm_cropY'],
                'w' => $_POST['AvatarForm_cropW'],
                'h' => $_POST['AvatarForm_cropH'],);
            Yii::import("ext.yii-jcrop.EJCropper");
            $crop = new EJCropper();
            $crop->targ_w = $width;
            $crop->targ_h = $height;
            $crop->thumbPath = $pathThumb;
            $crop->destName = $name;
            $thumb_name = $crop->crop($image, $coords);
            return $thumb_name;
        } else {
            return false;
        }
    }

    protected function CropingKtp($image, $pathThumb, $name, $width, $height) {
        if (isset($_POST['cropKtp'])) {
            if (!file_exists($pathThumb)) {
                mkdir($pathThumb, 0777, true);
            }
            $coords = array(
                'x' => $_POST['KtpForm_cropX'],
                'y' => $_POST['KtpForm_cropY'],
                'w' => $_POST['KtpForm_cropW'],
                'h' => $_POST['KtpForm_cropH'],);
            Yii::import("ext.yii-jcrop.EJCropper");
            $crop = new EJCropper();
            $crop->targ_w = $width;
            $crop->targ_h = $height;
            $crop->thumbPath = $pathThumb;
            $crop->destName = $name;
            $thumb_name = $crop->crop($image, $coords);
            return $thumb_name;
        } else {
            return false;
        }
    }

    public function actionUpload() {
        $base = app()->basePath;
        Yii::import("ext.EAjaxUpload.qqFileUploader");
        $folder = $this->dir_img_tmp_full . '/'; // folder for uploaded files
        $allowedExtensions = array("jpg", "jpeg", "gif", "png"); //array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 1 * 1024 * 1024; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder, true);
        $fileSize = filesize($folder . $result['filename']); //GETTING FILE SIZE
        $fileName = $result['filename']; //GETTING FILE NAME
        $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        echo $result; // it's array
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     *
     * @param integer $id the ID of the model to be loaded
     *
     * @return Jamaah the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = Jamaah::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     *
     * @param Jamaah $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'jamaah-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
